
#include <string.h>
#include <strings.h>

#include "String.hh"

void mtool::String::trim(){
	this->ltrim();
	this->rtrim();
}


void mtool::String::ltrim(){
	size_t i=0;
	size_t os=this->size(); //old size
	char str[os];
	if(os==0 || this->at(0)!=' ')  return ; //nothing to do
	for(i=0;i<os;i++){
		if(this->at(i)!=' '){   memmove(&(this->at(0)),&(this->at(i)),os-i);break;}
	}
	this->resize( os-i );

}



void mtool::String::rtrim(){
	size_t i;
	size_t os=this->size(); //old size

	for(i=os-1;i>=0;i--)
		if(this->at(i)!=' ') {  break; }
	this->resize( i+1 );
}


const int  mtool::String::casecompare (const char* s){
	return strcasecmp(this->c_str(),s);
}


mtool::StringRef::StringRef(const char * ref,size_t s){
	this->pos=ref;
	this->size=s;
}

std::string mtool::StringRef::toString(){
	if(pos &&size!=-1 )  return std::string(pos,size);
	return std::string();
}

mtool::StringRef::StringRef(){
}

mtool::StringRef::StringRef(const char *s){
	this->pos=s;
	this->size=strlen(s);
}


const char * mtool::StringRef::c_str(){
	return pos;
}

#define MIN(a,b)  (((a) < (b)) ? (a) : (b))
bool mtool::StringRef::Compare(StringRef a,StringRef b){
	
	size_t m=MIN(a.size,b.size);
	int r=strncmp(a.pos,b.pos,m);
	if(r>0)  return true;
	if(a.size>b.size)  return true;	
	return false;
	
	
	
}

bool mtool::StringRef::instr(const char * s){
	size_t l1=strlen(s);
	if(l1>size) return false;

	size_t d=size-l1;
	for(int i=0;i<=d;i++){
		if(strncmp(pos+i,s,l1)==0)  return true;
		else   return false;
	}
	
}


bool mtool::StringRef::operator<(const mtool::StringRef & a) const{
	size_t m=MIN(a.size,size);
	int r=strncmp(pos,a.pos,m);
	if(r>0)  return true;
	if(size>a.size) return true;
	return false;
}



bool mtool::StringRef::Equal(const char * str){
	if(str==NULL ) return false;
	size_t s=strlen(str);
	if(s!=size) return false;
	if(strncmp( str,pos,s)==0) return true;
	return false;
}


bool mtool::StringRef::CaseEqual(const char * str){
	if(str==NULL ) return false;
	size_t s=strlen(str);
	if(s!=size) return false;
	if(strncasecmp( str,pos,s)==0) return true;
	return false;
}

